/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { Scene, SceneConfig } from "../../ArkAnalyzer/src";
import { GraphBuilder } from "../../Ark2Graph/graphBuilder";
import { describe, expect, test, beforeAll, afterAll } from "@jest/globals";
import path from "path";
import fs from "fs";
import { Connection } from "../../Ark2Graph/Client";

const testConfigs = [
  "TestDFGConfig.json",
  "TestNoDFGConfig.json"
];

describe.each(testConfigs)("DFG Builder Test with %s", (configFile: string) => {
  let client: any;
  let graphBuilder: GraphBuilder;
  let DFGCount: any;
  
  const DFGquery = `.E().has('type', 'dfg').count()`;
  const cypherBatch = 'g';

  beforeAll(async () => {
    client = await Connection.getClient();
    const configPath = path.resolve(__dirname, `../test_config/${configFile}`);
    graphBuilder = new GraphBuilder(client, configPath);
    const configfile = JSON.parse(fs.readFileSync(configPath, "utf-8"));
    const filePath = configfile.fileTestConfigPath;
    let config: SceneConfig = new SceneConfig();
    config.buildFromJson(filePath);
    config.buildFromProjectDir(config.getTargetProjectDirectory());
    let scene = new Scene();
    scene.buildSceneFromProjectDir(config);
    graphBuilder.setScene(scene);

    // Only build CPG for TestDFGConfig
    if (configFile === "TestDFGConfig.json") {
      await graphBuilder.buildCPG();
      DFGCount = await client.submit(cypherBatch + DFGquery);
    } else {
      DFGCount = { _items: [0] }; // Default to 0 edges for NoDFG
    }
  });

  afterAll(async () => {
    //if (client) {
      await client.close();
    //}
  });

  test("should initialize GraphBuilder correctly", () => {
    expect(graphBuilder).toBeDefined();
  });

  // Expected values for each test config
  const expectedValues = {
    "TestDFGConfig.json": { dfg: 66 },
    "TestNoDFGConfig.json": { dfg: 0 }
  };

  test("should build DFG edges correctly", () => {
    expect(DFGCount._items[0]).toBe(
      expectedValues[configFile as keyof typeof expectedValues].dfg
    );
  });
});
